<template> 
  <div>
    <el-upload
      ref="upload"
      :action="action"
      :data="dataObj"
      :list-type="listType"
      :file-list="fileList"
      :show-file-list="showFile"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      multiple>

      <!-- <el-button type="primary" v-show="listType == 'picture'">{{clickText}}</el-button>
      <div slot="tip" class="el-upload__tip" v-show="listType == 'picture'">只能上传单文件<a style="color: #409EFF"
                                                                                      @click="iconClick"></a></div>
      <div class="avatarBox" v-show="listType != 'picture'">
        <img v-if="fileList.length >0" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus"></i>
      </div> -->

      <el-button type="primary" size="small">{{clickText}}</el-button>
      <!-- <el-button type="primary"></el-button> -->
  <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
    </el-upload>
    <!-- <el-dialog :append-to-body="true" :visible.sync="dialogVisible">
      <img width="100%" :src="fileList.length >0 ? fileList[0].url:''" alt="">
    </el-dialog>
    <icon-dialog ref="iconDialog" @confirm="dialogConfirm"/> -->
  </div>
</template>
<script>
  import {policy} from '@/api/oss'
  import IconDialog from '@/components/IconDialog'
  import utils from '../../utils/utils'

  export default {
    name: 'singleUpload',
    props: {
      value: "" ,
      listType: {
        type: String,
        default: 'picture'
      },
      clickText: {
        type: String,
        default: '点击上传'
      }, // 按钮名称
      showFile:{// 是否显示文件列表
        type: Boolean
      }, 
    },
    watch: {
      value: {
        handler(newVal, oldVal) {
          console.log('newVal--',newVal,typeof(newVal));
          console.log('oldVal--',oldVal);
          if(typeof(newVal) == 'string'){
            newVal = JSON.parse(newVal)
          }
          if (newVal.length > 0) {
            this.first = false;//用变量控制第一次才改变值
            this.fileList = newVal
          }
        },
        immediate: true
      },
      listType: {
        /*handler(newVal, oldVal) {
            if(newVal == 'picture'){
                this.showFile = true
            }else {
                this.showFile = false
            }
        },
        immediate: true*/
      },
    },
    computed: {
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value != null && this.value !== '') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null;
        }
      },
    },
    components: {
      IconDialog
    },
    data() {
      return {
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: ''
        },
        action: '',
        dialogVisible: false,
        fileList: [],
        first: true,
        uuid: ''
      };
    },
    methods: {
      iconClick() {
        this.$refs.iconDialog.show()
      },
      dialogConfirm(data) {
        this.fileList = [{name: data.name, url: data.iconUrl}];
        this.emitInput(this.fileList[0].url);
      },
      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput(fileList);
      },
      handlePreview(file) { // 预览
        // this.dialogVisible = true;
      },
      beforeUpload(file) {
        this.$emit('uploadFn', false)
        let _self = this;
        _self.uuid = utils.getUUID()
        console.log('fileList', this.fileList,file);
        console.log('showFileList', this.showFileList)
        // if (!utils.isNull(this.fileList[0].name) && !utils.isNull(this.fileList[0].url)) {
        //   this.handleRemove()
        // }
        // if ('file/jasper'.indexOf(file.type) == -1) {
        //   this.showFile = false
        //   _self.$message({
        //     message: "请上传.jasper格式的文件",
        //     offset: 120,
        //     center: true
        //   });
        //   return false;
        // } else {
          return new Promise((resolve, reject) => {
            policy().then(response => {
              _self.dataObj.policy = response.data.policy;
              _self.dataObj.signature = response.data.signature;
              _self.dataObj.ossaccessKeyId = response.data.accessKeyId;
              _self.dataObj.dir = response.data.dir;
              _self.dataObj.key = response.data.dir + '/' + _self.uuid + "${filename}";
              _self.dataObj.host = response.data.host;
              _self.action = response.data.action;
              resolve(true)
              this.$emit('uploadFn', true)
            }).catch(err => {
              console.log(err)
              reject(false)
            })
          })
        // }

      },
      handleChange(file, fileList) {
        console.log('上传文件变化file--',file);
        console.log('上传文件变化this.fileList--',fileList);
        // this.fileList = fileList.slice(-1);
      },
      handleUploadSuccess(res, file) {
        console.log('上传文件成功file--',file);
        console.log('上传文件成功this.fileList--',this.fileList);
        console.log('上传文件成功url--',this.dataObj.host + '/' + this.dataObj.dir + '/' + this.uuid + file.name);
        let item = {
          name: file.name,
          url: this.dataObj.host + '/' + this.dataObj.dir + '/' + this.uuid + file.name,
        }
        this.fileList.push(item)
        this.emitInput(this.fileList);
      }
    }
  }
</script>
<style scoped>
  .avatarBox {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .avatar {
    width: 99%;
    height: 99%;
    display: block;
  }

  .el-form-item__content .el-upload .el-button {
    background: #46a6ff;
    border-color: #46a6ff;
    margin: 0;
  }
</style>
